<?php
/**
 * Created by PhpStorm.
 * User: yiyu
 * Email: smalleasyu@gmail.com
 * Date: 2020-02-03 13:18:19
 * Desc:
 */

namespace app\base\model\address;

use think\Model;
use think\Db;

class UserAddressInfo extends Model
{

    // 关闭自动写入时间戳
    protected $autoWriteTimestamp = false;

    protected $table = 'xy_address.xy_user_address_info';

    const MAX_ADDRESS_NUM = 30;

    public static function setDefaultAddress($address_id, $user_id)
    {
        Db::startTrans();

        try {
            $res = self::where('address_id', $address_id)->where('user_id', $user_id)->update(['is_default', 1]);

            if (!$res) {
                Db::rollback();
                return false;
            }
            //这里不需要判断，因为用户可能只有一条记录
            self::where('address_id', '<>', $address_id)->where('user_id', $user_id)->update(['is_default', 0]);
            Db::commit();
            return true;
        } catch (\exception $e) {
            Db::rollback();
            return false;
        }
    }

    public static function addressIsExists($where)
    {
        if (empty($where)) {
            return false;
        }

        if (!isset($where['address_id']) || empty($where['address_id'])) {
            return false;
        }

        $info = self::field('address_id')->where($where)->find();

        return $info ? true : false;

    }

    public static function getDefaultAddress($user_id)
    {
        return self::field('address_id,receive_name,receive_phone,postal_code,province_name,city_name,area_name,address_detail')->where('user_id',
            $user_id)->where('is_del', 0)->where('is_default', 1)->find();
    }

    public static function getEffectiveAddressNum($user_id)
    {
        return self::where('user_id', $user_id)->where('is_del', 0)->count();
    }

}